package com.gzq.singleton.practice1;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 单例设计模式： 饿汉式：静态常量、静态代码块 懒汉式：方法锁、双重校验锁、静态内部类。 枚举。
 * 
 * @author Administrator
 *
 */
public class StaticInnerClass implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args)
			throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException, ClassNotFoundException {
		StaticInnerClass singleton1 = StaticInnerClass.getSingleton();
		StaticInnerClass singleton2 = StaticInnerClass.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		Constructor<StaticInnerClass> declaredConstructor = StaticInnerClass.class.getDeclaredConstructor();
		StaticInnerClass newInstance = declaredConstructor.newInstance();
		System.out.println(newInstance);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);
		byte[] byteArray = baos.toByteArray();

		ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(bais);
		Object readObject = ois.readObject();
		System.out.println(readObject);
	}

	private StaticInnerClass() {
	}

	private static class InnerClass {
		private static StaticInnerClass singleton = new StaticInnerClass();
	}

	public static StaticInnerClass getSingleton() {
		return InnerClass.singleton;
	}
}
